package com.practice.Http.XML.Coder.Response;

import com.practice.Http.XML.Coder.AbstractHttpXmlEncoder;
import com.practice.Http.XML.Coder.POJO.HttpXmlResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.util.List;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpXmlResponseEncoder extends AbstractHttpXmlEncoder<HttpXmlResponse> {
    @Override
    protected void encode(ChannelHandlerContext ctx, HttpXmlResponse msg, List<Object> out) throws Exception {
        ByteBuf body = encode0(
                ctx,
                msg.getResult());
        FullHttpResponse response = msg.getResponse();
        if (response == null) {
            response = new DefaultFullHttpResponse(
                    HTTP_1_1,
                    HttpResponseStatus.OK,
                    body);
        } else {
            response = new DefaultFullHttpResponse(
                    msg.getResponse().getProtocolVersion(),
                    msg.getResponse().getStatus(),
                    body);
        }
        response.headers().set(
                HttpHeaders.Names.CONTENT_TYPE,
                "text/html");
        response.headers().set(
                HttpHeaders.Names.CONTENT_LENGTH,
                body.readableBytes());
        out.add(response);
    }
}
